﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
using System.Configuration;
using System.Xml;
using System.Drawing.Printing;
using System.Diagnostics;
using System.Threading;

namespace SMS
{
    public partial class SMSPrinter : Form

    {
        private StringBuilder m_Sb;
        private bool m_bDirty;
        private FileSystemWatcher m_Watcher;
        private bool m_bIsWatching;
        private StreamReader sr;
        private Font verdana10Font;
        public String FilePathName = @"c:\tvc-cards\";
        public String Log = @"C:\tvc-cards\Log";
        public StreamWriter SW;
        public String strDatetime;
        
       public SMSPrinter()
        {
          
            InitializeComponent();
            m_Sb = new StringBuilder();
            m_bDirty = false;
            m_bIsWatching = false;
            strDatetime = DateTime.Now.ToString().Replace(":","_");
            //StreamWriter file = new StreamWriter(Log + "\\test.txt");
            //file.Write("Test");
            //string Logpath = Log + "\\" + strDatetime + ".txt";
            //SW = File.CreateText(Logpath);
            //SW.WriteLine("God is greatest of them all");
            //SW.WriteLine("This is second line");                       
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (m_bIsWatching)
            {
                m_bIsWatching = false;
                m_Watcher.EnableRaisingEvents = false;
                m_Watcher.Dispose();
                btnStart.BackColor = Color.LightSkyBlue;
                btnStart.Text = "Start Watching";
                lbltext.Text = "To Start the Application Click on Start Button";
                SW.WriteLine("Application Stoped : "+ DateTime.Now.ToString());
                SW.Close();
            }
            else
            {
                string Logpath = Log + "\\" + strDatetime + ".txt";
                SW = File.CreateText(Logpath);
                    m_bIsWatching = true;
                    btnStart.BackColor = Color.Red;
                    btnStart.Text = "Stop Watching";
                    lbltext.Text = "To Stop the Application Click on Stop Button";
                    SW.WriteLine("Application Started : " + DateTime.Now.ToString());

                    string[] FILES = Directory.GetFiles(FilePathName);
                if(FILES.Length>0)
                {
                    if (FILES[0] != null)
                    {
                    }
                    foreach (string subfiles in FILES)
                    {
                        this.GenerateXML(subfiles, "exist");
                    }
                }                   
                    m_Watcher = new System.IO.FileSystemWatcher();
                    //if (rdbDir.Checked)
                    //{
                        m_Watcher.Filter = "*.*";
                        m_Watcher.Path = FilePathName;                           
                   //}
                    //else
                   // {
                   // m_Watcher.Filter = FilePathName.Substring(FilePathName.LastIndexOf('\\') + 1);
                    //m_Watcher.Path = FilePathName.Substring(0, FilePathName.Length - m_Watcher.Filter.Length);
                    //}

                    //if (chkSubFolder.Checked)
                    //{
                    //    m_Watcher.IncludeSubdirectories = true;
                    //}

                    m_Watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                                         | NotifyFilters.FileName | NotifyFilters.DirectoryName;
                    //m_Watcher.Changed += new FileSystemEventHandler(OnChanged);
                    m_Watcher.Created += new FileSystemEventHandler(OnChanged);
                
                    //m_Watcher.Deleted += new FileSystemEventHandler(OnChanged);
                    //m_Watcher.Renamed += new RenamedEventHandler(OnRenamed);
                    m_Watcher.EnableRaisingEvents = true;   
                        
            }
        }


        private void OnChanged(object sender, FileSystemEventArgs e)
        {
            try
            {
                if (!m_bDirty)
                {
                    m_Sb.Remove(0, m_Sb.Length);
                    m_Sb.Append(e.FullPath);
                    m_Sb.Append(" ");
                    m_Sb.Append(e.ChangeType.ToString());
                    m_Sb.Append("    ");
                    m_Sb.Append(DateTime.Now.ToString());
                    m_bDirty = true;
                    this.GenerateXML(e.FullPath, m_Sb.ToString());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void tmrEditNotify_Tick(object sender, EventArgs e)
        {
            if (m_bDirty)
            {
                //lstNotification.BeginUpdate();
                //lstNotification.Items.Add(m_Sb.ToString());
                //lstNotification.EndUpdate();
                m_bDirty = false;
            }
        }

        private void GenerateXML(string pStrFpath, string pStrMsg)
        {
            FileInfo lObjFInfo = null;
            
            try
            {
                lObjFInfo = new FileInfo(pStrFpath);

                if (lObjFInfo.Exists)
                {
                    if (lObjFInfo.Extension.Equals(".doc"))
                    
                    {
                        if (lObjFInfo.Length > 0)
                        {
                            if (this.ProcessFileContent(lObjFInfo, pStrMsg));
                                //this.BackUpFile(lObjFInfo);
                        }
                    }
                }
               
                
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (lObjFInfo.Extension.Equals(".pdf"))
                {
                    lObjFInfo.Delete();
                }
               
            }
        }

        private static void RunExecutable(string executable, string arguments)
        {
            ProcessStartInfo starter = new ProcessStartInfo(executable, arguments);
            starter.CreateNoWindow = true;
            starter.RedirectStandardOutput = true;
            starter.UseShellExecute = false;
            Process process = new Process();
            process.StartInfo = starter;
            process.Start();
            StringBuilder buffer = new StringBuilder();
            using (StreamReader reader = process.StandardOutput)
            {
                string line = reader.ReadLine();
                while (line != null)
                {
                    buffer.Append(line);
                    buffer.Append(Environment.NewLine);
                    line = reader.ReadLine();
                    Thread.Sleep(100);
                }
            }
        }
        private bool ProcessFileContent(FileInfo pObjFInfo, string pStrBodyMsg)
        {
            bool blnProcessStatus = false;
            //string BookingNum = string.Empty;
            try
            {
                SW.WriteLine(pObjFInfo.Name +" Printed at :"+ DateTime.Now.ToString());

                //RunExecutable("acrord32.exe", @"/t ""mytest.pdf"" ""My Windows PrinterName""");
                sr = pObjFInfo.OpenText();
                ////Create a Verdana font with size 10
                verdana10Font = new Font("Verdana", 10);
                ////Create a PrintDocument object
                PrintDocument pd = new PrintDocument();
                ////pd.PrinterSettings.PrinterName = "B2VOF Printer";
                ////Add PrintPage event handler
                //Process p = new Process();
                //ProcessStartInfo info = new ProcessStartInfo();
                //info.FileName = pObjFInfo.ToString();
                //info.Verb = "Print";
                
                //info.Arguments = pd.PrinterSettings.PrinterName;
                //info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                //p.StartInfo = info;
                //p.Start();

              pd.PrintPage += new PrintPageEventHandler(PrintTextFileHandler);
             
                //pd.PrinterSettings.PrinterName = "B2VOFPri";
                //Call Print Method
                pd.Print();
                //Close the read
                if (sr != null)
                    sr.Close();
                blnProcessStatus = true;


            }
            catch (Exception ex)
            {
                throw ex;
            }
            return blnProcessStatus;
        }

        private void PrintTextFileHandler(object sender, PrintPageEventArgs ppeArgs)
        {
            //Get the Graphics object
            Graphics g = ppeArgs.Graphics;
            float linesPerPage = 0;
            float yPos = 0;
            int count = 0;
            //Read margins from PrintPageEventArgs
            float leftMargin = ppeArgs.MarginBounds.Left;
            float topMargin = ppeArgs.MarginBounds.Top;
            string line = null;
            //Calculate the lines per page on the basis of the height of the page and the height of the font
            linesPerPage = ppeArgs.MarginBounds.Height /
            verdana10Font.GetHeight(g);
            //Now read lines one by one, using StreamReader
            while (count < linesPerPage &&
            ((line = sr.ReadLine()) != null))
            {
                //Calculate the starting position
                yPos = topMargin + (count *
                verdana10Font.GetHeight(g));
                //Draw text
                g.DrawString(line, verdana10Font, Brushes.Black,
                leftMargin, yPos, new StringFormat());
                //Move to next line
                count++;
            }
            //If PrintPageEventArgs has more pages to print
            if (line != null)
            {
                ppeArgs.HasMorePages = true;
            }
            else
            {
                ppeArgs.HasMorePages = false;
            }
        }

        private void BackUpFile(FileInfo pObjFInfo)
        {
            string lStrBackupFName = pObjFInfo.Name;
            string lStrFldName = this.GetValueFromConfig("Backup");
            pObjFInfo.CopyTo(lStrFldName + lStrBackupFName);
        }

        private string GetValueFromConfig(string pObjGetKey)
        {
           // return ConfigurationManager.AppSettings[pObjGetKey].ToString();
            return @"c:\Archive\";
        }

                       
    }
}
